package cn.xiyun.xiyuncc.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

/**
 * String 返回 BASE64二维码
 * @Author maple
 * @Date 2021/12/3 15:34
 * @Version 1.0
 */
/*
 <!-- 二维码-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.2</version>
        </dependency>
*/
@Slf4j
@Component
public class QRCodeUtil {
    /**
     * 创建二维码
     * @return
     */
    public static void outputImage(String str, int width, int height, OutputStream os)throws Exception{
        BufferedImage image = null;
        try {
            // 生成二维码
            BitMatrix byteMatrix = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE,width,height);
            // 生成流
            MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig();
            image = MatrixToImageWriter.toBufferedImage(byteMatrix, matrixToImageConfig);

        } catch (WriterException e) {
            e.printStackTrace();
        }

        ImageIO.write(image, "jpg", os);
    }

    /**
     * String 返回 BASE64
     * @param str
     * @param width
     * @param height
     * @return
     */
    public static String getQR(String str, int width, int height)  {
        //创建一个 BASE64编码器
        BASE64Encoder encoder = new BASE64Encoder();
        //二进制输出流，用来装图片的
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        //画一个w宽，h高的图片，把code画上去，然后把图片写入 data
        try {
            outputImage(str,width, height, data);
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new RuntimeException("图验证码创建失败");
        }
        //把data(图片）进行base64编码
        return encoder.encode(data.toByteArray());
    }

}
